package cz.mpelant.msoe.mealchecker.downloader;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class JsonRequest extends DownloadRequest {
	public static class JsonCall {
		private String method;
		private JSONObject params;

		public JsonCall(String method, JSONObject params) {
			super();
			this.method = method;
			this.params = params;
		}

		public String getMethod() {
			return method;
		}

		public void setMethod(String method) {
			this.method = method;
		}

		public JSONObject getParams() {
			return params;
		}

		public void setParams(JSONObject params) {
			this.params = params;
		}

	}

	private List<JsonCall> jsonCalls;
	private int jsonId = 1;
	private String TAG = "JsonRequest";

	public JsonRequest(String url, OutputStream os, String id) {
		super(new HttpPost(url), os, id);
		jsonCalls = new ArrayList<JsonRequest.JsonCall>();
	}

	public void addCall(JsonCall call) {
		jsonCalls.add(call);
	}

	protected JSONObject createMethodCall(JsonCall call) {
		JSONObject json = null;
		try {
			json = new JSONObject();
			json.put("jsonrpc", "2.0");
			json.put("method", call.getMethod());
			json.put("params", call.getParams());
			json.put("id", jsonId);
		} catch (JSONException e) {
		}

		return json;
	}

	public String getJsonString() throws JSONException {
		JSONArray jsa =  new JSONArray();
		for (JsonCall jsonCall : jsonCalls) {
			jsa.put(createMethodCall(jsonCall));
		}
		return jsa.toString();
	}

	@Override
	public HttpUriRequest getHttpRequest() {
		HttpPost request = (HttpPost) httpRequest;
		try {
			request.setEntity(new StringEntity(getJsonString(), HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();

		}
		request.addHeader("Accept", "application/json");
		request.addHeader("Content-type", "application/json;charset=UTF-8");
		return request;
	}

}
